<template>
  <div>
    <el-row>
      <el-col :sm="8">
        <div class="g-title">年度配备更新计划管理数（{{total}}个）</div>
      </el-col>
      <el-col :sm="16" style="text-align: right;">
        <el-button type="primary" @click="add" size="small">新增</el-button>
        <el-button type="danger" @click="edit" size="small">修改</el-button>
        <el-button type="warning" @click="del_plan" size="small">删除</el-button>
        <el-button type="success" @click="exportData" size="small">导出</el-button>
      </el-col>
    </el-row>
    <el-table
      ref="multipleTable"
      :data="listData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :border="true"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="index" label="序号"></el-table-column>
      <el-table-column prop="year" label="年度" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column prop="userName" label="经办人" align="center"></el-table-column>
      <el-table-column prop="carNum" label="更新车辆数" align="center"></el-table-column>
      <el-table-column prop="totalprice" label="经费预算(万元)" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column prop="createDate" label="发起时间" show-overflow-tooltip align="center"></el-table-column>
    </el-table>

    <el-row style="padding: 32px 16px;">
      <el-col>
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-size="pageSize"
          :total="total"
          :current-page="pageNo"
          @current-change="fetchData"
          @size-change="pageSizeChange"
        ></el-pagination>
      </el-col>
    </el-row>
    <el-dialog
      title="发起计划"
      ref="tableDialog"
      :visible.sync="dialogVisible"
      width="50%"
      v-if="formData"
    >
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="form">
        <el-row>
          <el-col :sm="24">
            <el-form-item label="年度" prop="year">
              <el-select v-model="formData.year" placeholder="请选择年度" style="width: 100%;">
                <el-option
                  :label="item.year"
                  :value="item.year"
                  v-for="(item, index) in years"
                  :key="item.year"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :sm="24">
            <el-form-item label="筛选">
              <el-table
                ref="multipleTable"
                :data="tableData"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange"
                :header-cell-style="{background:'#fff'}"
              >
                <el-table-column label="车型" prop="car_type" align="center"></el-table-column>

                <el-table-column prop="reason" label="大于行驶里程(公里)" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.gonum" type="number"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="time" label="等级年限(年)" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.year" type="number"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :sm="24"></el-col>
          <el-form-item label>
            <el-button type="primary" @click="saveadd">保存数据</el-button>
            <el-button @click="resetForm">重置表单</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
    <el-dialog title="确认计划更新车辆" :visible.sync="edit_dialog" width="80%">
      <el-dialog
        append-to-body
        title="车辆信息"
        ref="tableDialog"
        :visible.sync="car_add"
        width="80%"
        v-if="formData"
      >
        <el-form label-width="100px" ref="form">
          <el-row>
            <el-col :sm="6" style="padding:0px 5px">
              <el-select v-model="req_data.useAttrId" placeholder="请选择使用性质" style="width: 100%;">
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in types"
                  :key="item.sname"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :sm="6" style="padding:0px 5px">
              <el-select v-model="req_data.carTypeId" placeholder="请选择车型" style="width: 100%;">
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in cartype"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :sm="6" style="padding:0px 5px">
              <el-select v-model="req_data.carClassId" placeholder="请选择动力类型" style="width: 100%;">
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in power"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :sm="6" style="padding:0px 5px">
              <el-button type="danger" size="small" @click="clfetchData()">查询</el-button>
              <el-button type="warning" size="small" @click="selectAdd()">确认选择</el-button>
              <el-button size="small" @click="resetChoose()">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-row>
          <el-col :sm="8">
            <div class="g-title">车辆数目（{{cl_total}}个）</div>
          </el-col>
          <br />
          <br />
          <el-table
            ref="multipleTable"
            :border="true"
            :data="car_list"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="carSelectionChange"
            :header-cell-style="{background:'#F5F7FA'}"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" prop="index"></el-table-column>
            <el-table-column prop="carCode" label="车牌号"></el-table-column>
            <el-table-column prop="companyName" label="所属单位名称"></el-table-column>
            <el-table-column prop="useType" label="车辆使用性质"></el-table-column>
            <el-table-column prop="pinpai" label="厂牌型号"></el-table-column>
            <el-table-column prop="fromCode" label="车架号"></el-table-column>
            <el-table-column prop="machineCode" label="发动机号"></el-table-column>
            <el-table-column prop="jingFei" label="经费来源"></el-table-column>
            <el-table-column prop="type" label="购置方式"></el-table-column>
            <el-table-column prop="createTime" label="创建时间"></el-table-column>
          </el-table>
          <el-row style="padding: 32px 16px;">
            <el-col>
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :page-size="cl_pageSize"
                :total="cl_total"
                :current-page="cl_pageNo"
                @current-change="clfetchData"
                @size-change="clpageSizeChange"
              ></el-pagination>
            </el-col>
          </el-row>
        </el-row>
      </el-dialog>
      <el-form>
        <el-row>
          <el-col :sm="24">年度：{{formData.year}}</el-col>
          <br />
          <br />
          <el-col :sm="24">
            <el-table
              ref="multipleTable"
              :data="edit_Data1"
              tooltip-effect="dark"
              style="width: 100%"
            >
              <el-table-column prop="propName" label="车型" align="center"></el-table-column>
              <el-table-column prop="goNum" label="已行驶公里数" align="center"></el-table-column>
              <el-table-column prop="regYear" label="已行驶年限" align="center"></el-table-column>
            </el-table>
            <br />
            <br />
          </el-col>
          <br />
          <el-row>
            <el-col :sm="8">
              <div class="g-title">计划内车数量（{{etotal}}个）</div>
            </el-col>
            <el-col :sm="16" style="text-align: right;">
              <el-button type="success" @click="add_plan" size="small">新增</el-button>
              <el-button type="danger" @click="del_plancar" size="small">移除</el-button>
            </el-col>
          </el-row>

          <br />
          <el-table
            ref="multipleTable"
            :data="edit_Data2"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="plancarSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" prop="cars.index"></el-table-column>
            <el-table-column prop="cars.companyName" label="单位名称"></el-table-column>
            <el-table-column prop="cars.carCode" label="车牌号"></el-table-column>
            <el-table-column label="车型" prop="cars.carType"></el-table-column>
            <el-table-column prop="cars.goNum" label="行驶里程"></el-table-column>
            <el-table-column prop="cars.useType" label="使用性质"></el-table-column>
            <el-table-column prop="cars.discharge" label="排气量"></el-table-column>
            <el-table-column label="更新预算">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.price"
                  type="text"
                  @blur="changeprice(scope.row)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="car_info(scope.row.cars.id)">车辆详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row style="padding: 32px 16px;">
            <el-col>
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :page-size="epageSize"
                :total="etotal"
                :current-page="epageNo"
                @current-change="efetchData"
                @size-change="epageSizeChange"
              ></el-pagination>
            </el-col>
          </el-row>
        </el-row>
      </el-form>
    </el-dialog>
    <el-dialog title="车辆信息" :visible.sync="carinfo" width="80%">
      <carInfos v-if="carinfo" :carId="carId" @close2="carinfo=false"></carInfos>
    </el-dialog>
  </div>
</template>
<style>
[v-cloak] {
  display: none;
}

@media screen and (min-width: 992px) {
  .modal-dialog {
    width: 992px;
  }
}

.g-title {
  height: 20px;
  padding-left: 8px;
  line-height: 22px;
  font-size: 16px;
  font-weight: 400;
  border-left: 2px solid #f54e40;
  margin: 10px 0;
  display: inline-block;
}

.el-table th {
  background-color: #f5f7fa;
}

.el-dialog {
  -webkit-transform: none;
  transform: none;
  left: 0;
  position: relative;
  margin: 0 auto;
  background: #eef1f6;
}

.el-dialog__body {
  background-color: white;
  margin: 0px 10px;
}

.eluploadwrapper {
  display: inline-block;
  margin-left: 10px;
}
</style>
<script>
import { axios_req } from "@/api/carcommon";
import { mapGetters } from "vuex";
import carInfos from "../../../companyset/components/carinfo/index";
export default {
  components: { carInfos },
  computed: {
    ...mapGetters(["userInfo"])
  },
  data: function() {
    return {
      tabIndex: "1",
      username: "",
      dialogVisible: false,
      roleDialogVisible: false,
      edit_dialog: false,
      car_add: false,
      carinfo: false,
      total: 1,
      cl_total: 3,
      etotal: 0,
      pageNo: 1,
      cl_pageNo: 1,
      epageNo: 1,
      pageSize: 10,
      cl_pageSize: 10,
      epageSize: 10,
      allCars: [],
      selectedCars: [],
      src:
        "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1590668058341&di=97ba08fee5f4e68e8f283eba07136d6c&imgtype=0&src=http%3A%2F%2Fsecretkeycrm.digifilm.com.cn%2Fupload%2F20180530%2Fe676f667c4cdfc7e074898adab2622f2.jpg",
      listData: [], //全部数据
      listDataSelected: [], //选中数据
      carSelected: [], //选中数据
      plancarSelected: [],
      formData: [],
      edit_Data1: [],
      edit_Data2: [],
      uploadFileParams: {
        a: 1
      }, //上传文件的额外参数
      headers: {
        cookie: ""
      },
      tableData: [
        {
          car_type_id: 5,
          car_type: "其它小型客车",
          gonum: "",
          year: ""
        },
        {
          car_type_id: 11,
          car_type: "轿车",
          gonum: "",
          year: ""
        },
        {
          car_type_id: 69,
          car_type: "中型客车",
          gonum: "",
          year: ""
        },
        {
          car_type_id: 70,
          car_type: "大型客车",
          gonum: "",
          year: ""
        },
        {
          car_type_id: 71,
          car_type: "其它",
          gonum: "",
          year: ""
        }
      ],
      //单位列表
      years: [
        {
          year: "2019"
        },
        {
          year: "2020"
        },
        {
          year: "2021"
        },
        {
          year: "2022"
        },
        {
          year: "2023"
        },
        {
          year: "2024"
        },
        {
          year: "2025"
        },
        {
          year: "2026"
        },
        {
          year: "2027"
        },
        {
          year: "2028"
        },
        {
          year: "2029"
        }
      ],
      formRules: {
        year: [
          {
            required: true,
            message: "请选择年度",
            trigger: "blur"
          }
        ]
      },
      types: [],
      cartype: [],
      power: [],
      car_list: [],
      addMode: false,
      req_data: {
        useAttrId: "",
        carTypeId: "",
        carClassId: ""
      },
      addplan: {
        carIds: "",
        planId: ""
      },
      carId: ""
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    async fetchData(pageNo) {
      if (pageNo) {
        this.pageNo = pageNo;
      }
      // console.log(this.userInfo.comid)
      let url = "/admin/carplan/listJson.do";
      let method = "GET";
      let params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        companyId:this.userInfo.comid
      };
      console.log(params)
      let data = await axios_req(url, method, params);
      console.log(data);
      this.listData = data.data;
      var nums = data.carNums;

      for (var i in this.listData) {
        for (var j in nums){
          if(nums[j].id == this.listData[i].id){
            this.listData[i].carNum = nums[j].carNum
          }
        }
        this.listData[i].index =
          Number(i) + Number(this.epageSize * (this.epageNo - 1)) + 1;
      }
      this.total = data.total;
      this.listDataSelected.splice(0);
    },
    async efetchData(pageNo) {
      if (pageNo) {
        this.epageNo = pageNo;
      }
    },
    async clfetchData(pageNo) {
      if (pageNo) {
        this.cl_pageNo = pageNo;
      }
      console.log(this.userInfo)
      let url = "/admin/carplan/findCars.do";
      let method = "POST";
      let params = {
        pageNo: this.cl_pageNo,
        pageSize: this.cl_pageSize,
        useAttrId: this.req_data.useAttrId,
        carTypeId: this.req_data.carTypeId,
        carClassId: this.req_data.carClassId,
        companyId:this.userInfo.comid
      };
      console.log(params);
      let data = await axios_req(url, method, params);
      console.log(data);
      this.car_list = data.data;
      for (var i in this.car_list) {
        this.car_list[i].index =
          Number(i) + Number(this.cl_pageSize * (this.cl_pageNo - 1)) + 1;
      }
      this.cl_total = data.total;
      // this.listDataSelected.splice(0);
    },

    //计划内添加车辆
    async selectAdd() {
      var carstr = "";
      if (this.carSelected.length == 0) {
        this.$message("请选择行数据");
        return;
      }
      this.carSelected.forEach(function(e) {
        carstr = carstr + "," + e.id;
      });
      carstr = carstr.replace(/^,+/, "").replace(/,+$/, "");
      this.addplan.carIds = carstr;
      let url = "/admin/carplan/addPlanCar.do";
      let method = "POST";
      let params = this.addplan;
      let data = await axios_req(url, method, params);
      if (data.error == 0) {
        this.$message({
          type: "success",
          message: "添加成功!"
        });
        this.edit_info(this.listDataSelected[0]["id"]);
        this.car_add = false;
        this.fetchData()
      } else {
        this.$message({
          type: "info",
          message: "添加失败"
        });
      }
    },
    car_info(info) {
      this.carId = info;
      this.carinfo = true;
    },
    async add_plan() {
      let url = "/admin/carplan/carDetails.do";
      let method = "GET";
      let params = {};
      let data = await axios_req(url, method, params);
      this.types = data.useAttrs;
      this.cartype = data.carTypes;
      this.power = data.carClasses;
      console.log(data);
      this.clfetchData();
      this.car_add = true;
    },
    add() {
      (this.formData = {
        year: "",
        person: "",
        new_car: "",
        money: "",
        time: ""
      }),
        (this.addMode = true);
      this.dialogVisible = true;
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    resetChoose() {
      // this.$refs.form.resetFields();
      this.req_data.useAttrId = '';
      this.req_data.carTypeId = '';
      this.req_data.carClassId = ''
      this.clfetchData()
    },
    del_plan() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择行数据");
        return;
      }

      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.del();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async del() {
      var del_str = "";
      this.listDataSelected.forEach(function(e) {
        del_str = del_str + "," + e.id;
      });
      del_str = del_str.replace(/^,+/, "").replace(/,+$/, "");
      let url = "/admin/carplan/removePlan.do";
      let method = "post";
      let params = {
        planIds: del_str
      };
      let data = await axios_req(url, method, params);
      if (data.error == 0) {
        this.$message({
          type: "success",
          message: "删除成功!"
        });
        this.fetchData();
      } else {
        this.$message({
          type: "info",
          message: "删除失败"
        });
        this.fetchData();
      }
    },

    del_plancar() {
      if (this.plancarSelected.length == 0) {
        this.$message("请选择行数据");
        return;
      }

      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.dels();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async dels() {
      var del_str = "";
      this.plancarSelected.forEach(function(e) {
        del_str = del_str + "," + e.id;
      });
      del_str = del_str.replace(/^,+/, "").replace(/,+$/, "");
      let url = "/admin/carplan/removePlanCar.do";
      let method = "post";
      let params = {
        planCarIds: del_str
      };
      let data = await axios_req(url, method, params);
      if (data.error == 0) {
        this.$message({
          type: "success",
          message: "删除成功!"
        });
        this.edit_info(this.listDataSelected[0]["id"]);
      } else {
        this.$message({
          type: "info",
          message: "删除失败"
        });
        this.edit_info(this.listDataSelected[0]["id"]);
      }
    },

    async changeprice(info) {
      let url = "/admin/carplan/changePlanMoney.do";
      let method = "POST";
      let params = {
        planCarId: info.id,
        Money: parseFloat(info.price)
      };
      console.log(params);
      let data = await axios_req(url, method, params);
      console.log(data);
      if (data.error == 0) {
        this.$message({
          message: "修改成功",
          type: "success"
        });
        this.fetchData()
      } else {
        this.$message("修改失败");
      }
    },
    edit() {
      //   this.fetchPlanList();
      if (this.listDataSelected.length == 0) {
        this.$message("请选择行数据");
        return;
      }
      this.formData = JSON.parse(JSON.stringify(this.listDataSelected[0]));
      this.edit_info(this.listDataSelected[0]["id"]);
      this.addplan.planId = this.listDataSelected[0]["id"];
      this.addMode = false;
      this.edit_dialog = true;
    },
    async edit_info(id) {
      let url = "/admin/carplan/findDetails.do";
      let method = "POST";
      let params = {
        planId: id
      };
      let data = await axios_req(url, method, params);
      this.edit_Data1 = data.items;
      this.edit_Data2 = data.data;
      console.log(this.edit_Data2);
      for (var i in this.edit_Data2) {
        this.edit_Data2[i]["cars"].index =
          Number(i) + Number(this.pageSize * (this.pageNo - 1)) + 1;
      }
      this.etotal = data.data.length;
    },
    async saveadd() {
      var strpost = "";
      if(!this.formData.year){
        this.$message("请选择年份");
        return
      }
      var sign = 0
      this.tableData.forEach(e => {
        if(e.gonum && e.gonum>=0 && e.year && e.year>=0){
          var str = e.car_type_id + "," + e.gonum + "," + e.year + ";";
          strpost = strpost + str;
        }
        if((e.gonum && !e.year) || (!e.gonum && e.year)){
          sign = sign+1
          
        }
      });
      if(!strpost){
        this.$message("请至少填入一条车型数据");
        return
      }
      if(sign>0){
          this.$message("请确认行内填写完整");
          return
      }
      let url = "/admin/carplan/addPlan.do";
      let method = "POST";
      let params = {
        year: this.formData.year,
        params: strpost,
        userId: this.userInfo.userid
      };
      let data = await axios_req(url, method, params);
      if (data.error == 0) {
        this.$message({
          message: "添加成功",
          type: "success"
        });
        this.dialogVisible = false;
        this.fetchData();
      } else {
        this.$message("添加失败");
      }
    },

    handleSelectionChange(val) {
      this.listDataSelected.splice(0);
      val.forEach(e => {
        this.listDataSelected.push(e);
      });
    },

    carSelectionChange(val) {
      this.carSelected.splice(0);
      val.forEach(e => {
        this.carSelected.push(e);
      });
    },
    plancarSelectionChange(val) {
      this.plancarSelected.splice(0);
      val.forEach(e => {
        this.plancarSelected.push(e);
      });
    },
    pageSizeChange(newSize) {
      this.pageSize = newSize;
      this.pageNo = 1;
      this.fetchData();
    },
    epageSizeChange(newSize) {
      this.epageSize = newSize;
      this.epageNo = 1;
      this.efetchData();
    },
    clpageSizeChange(newSize) {
      this.cl_pageSize = newSize;
      this.cl_pageNo = 1;
      this.clfetchData();
    },
    exportData() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择行数据");
        return;
      }
      var headers = "年度,经办人,更新车辆数,经费预算（万元）,发起时间";
      var data = this.listDataSelected.map(function(e) {
        return {
          year: e.year || "",
          userName: e.userName || "",
          new_car: e.new_car || "",
          totalprice: e.totalprice || "",
          createDate: e.createDate || ""
        };
      });
      this.jsonToExcel(data, headers);
    },
    //json导出excel
    jsonToExcel(jsonData, headers) {
      //列标题，逗号隔开，每一个逗号就是隔开一个单元格
      var str = headers + "\n";
      //增加\t为了不让表格显示科学计数法或者其他格式
      for (var i = 0; i < jsonData.length; i++) {
        for (var item in jsonData[i]) {
          str += jsonData[i][item] + "\t,";
        }
        str += "\n";
      }
      //encodeURIComponent解决中文乱码
      var uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);
      //通过创建a标签实现
      var link = document.createElement("a");
      link.href = uri;
      //对下载的文件命名
      link.download = "导出数据表.csv";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
};
</script>